package com.zhou.JavaAndroidFirm.model;

import com.zhou.JavaAndroidFirm.bean.NewsDetail;
import com.zhou.JavaAndroidFirm.constract.NewsDetailContract;
import com.zhou.JavaAndroidFirm.http.HttpService;
import com.zhou.JavaAndroidFirm.http.HttpUtils;
import com.zhou.JavaAndroidFirm.rx.RxSchedulers;

import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.functions.Func1;

import static com.zhou.JavaAndroidFirm.http.ApiConstants.NETEAST_HOST_BASEURL;

/**
 * @author Administrator
 * @date 2018/8/21 0021
 * @des
 */
public class NewsDetailModel implements NewsDetailContract.Model {
    @Override
    public Observable<NewsDetail> getOneNewsData(final String postId) {
        return HttpUtils.getInstance().getRetofitClinet().setBaseUrl(NETEAST_HOST_BASEURL)
                .builder(HttpService.class).getNewDetail(postId)
                .map(new Func1<Map<String, NewsDetail>, NewsDetail>() {
                    @Override
                    public NewsDetail call(Map<String, NewsDetail> stringNewsDetailMap) {
                        NewsDetail detail = stringNewsDetailMap.get(postId);
                        changeNewsDetail(detail);

                        return detail;
                    }
                }).compose(RxSchedulers.<NewsDetail>io_main());
    }

    private void changeNewsDetail(NewsDetail newsDetail) {
        List<NewsDetail.ImgBean> imgBeans = newsDetail.getImg();
        if (isChange(imgBeans)) {
            String newsBody = newsDetail.getBody();
            newsBody = changeNewsBody(imgBeans, newsBody);
            newsDetail.setBody(newsBody);
        }
    }

    private String changeNewsBody(List<NewsDetail.ImgBean> imgSrcs, String newsBody) {
        for (int i = 0; i < imgSrcs.size(); i++) {
            String oldChars = "<!--IMG#" + i + "-->";
            String newChars;
            if (i == 0) {
                newChars = "";
            } else {
                newChars = "<img src=\"" + imgSrcs.get(i).getSrc() + "\" />";
            }
            newsBody = newsBody.replace(oldChars, newChars);

        }
        return newsBody;
    }

    private boolean isChange(List<NewsDetail.ImgBean> imgSrcs) {
        return imgSrcs != null && imgSrcs.size() >= 2;
    }
}
